package net.caixiaomi.info.ui.login;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;

import net.caixiaomi.info.R;
import net.caixiaomi.info.WebViewActivity;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.base.BaseAlertDialog;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.UserInfoModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.EventWhat;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.info.widgets.DefLoading;
import net.caixiaomi.info.widgets.InputEditTextWatcher;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 注册
 */

public class RegistActivity extends BaseActivity implements TextWatcher {
    @BindView(R.id.phone)
    EditText mPhone;
    @BindView(R.id.phone_state)
    View mPhoneState;
    @BindView(R.id.btn_delete)
    View mBtnDelete;

    @BindView(R.id.lock_state)
    View mLockState;

    @BindView(R.id.key_state)
    View mKeyState;

    @BindView(R.id.password)
    EditText mPassword;

    @BindView(R.id.code)
    EditText mCode;

    @BindView(R.id.btn_send)
    TextView mBtnSendCode;
    @BindView(R.id.btn_selected)
    View mBtnSelected;
    @BindView(R.id.text)
    TextView mText;
    @BindView(R.id.btn_protocol)
    TextView mBtnProtocol;

    /**
     * 注册协议
     */
    @OnClick(R.id.btn_protocol)
    void toProtocol() {
        AppHelper.sendStatistics("zcyonghuxueyi");
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(Constants.BASE_H5_URL).append(getString(R.string.H5_REGISTER_SERVICE));
        String url = stringBuilder.toString();
        Intent intent = new Intent(this, WebViewActivity.class);
        intent.putExtra("url", url);
        startActivity(intent);
    }

    @OnClick(R.id.btn_selected)
    void toAgreeServiceProcotol(View view) {
        view.setSelected(!view.isSelected());
        if (!view.isSelected()) {
            ToastUtil.s(R.string.C_REGISTER_SERVICE_PROTOCOL_TIP);
        }
    }

    private CountDownTimer mCountDownTimer = new CountDownTimer(60 * 1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            StringBuilder stringBuilder = new StringBuilder();
            long second = millisUntilFinished / 1000;
            stringBuilder.append(getString(R.string.C_RESEND)).append(second).append("s");
            String text = stringBuilder.toString();
            SpannableString spannableString = new SpannableString(stringBuilder);
            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.orange_primary)), second < 10 ? text.length() - 2 : text.length() - 3, text.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            mBtnSendCode.setText(spannableString);
        }

        @Override
        public void onFinish() {
            mBtnSendCode.setText(getString(R.string.C_MESSAGE_CODE));
            mBtnSendCode.setEnabled(true);
        }
    };


    /**
     * 显示密码
     */
    @OnClick(R.id.btn_visibility)
    void toVisiblePassword(View view) {
        String password = mPassword.getText().toString().trim();
        if (!view.isSelected()) {
            mPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        } else {
            mPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }
        mPassword.setSelection(password.length());
        view.setSelected(!view.isSelected());
    }

    /**
     * 获取验证码
     */
    @OnClick(R.id.btn_send)
    void toSendCode() {
        String phone = mPhone.getText().toString().trim();

        if (!AppHelper.checkPhoneAvailable(phone)) {
            ToastUtil.s(R.string.C_PHONE_INVALID);
            return;
        }
        AppHelper.sendStatistics("zchuoquyzm", new String[]{getString(R.string.C_TERMINAL)}, new String[]{Build.BOARD});
        mLoading.show();
        JSONObject params = new JSONObject();
        params.put("smsType", "1");
        params.put("mobile", phone);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel> sendSmsCode = requestService.sendSmsCode(params);
        sendSmsCode.enqueue(new ResponseCallback<BaseCallModel>(this) {
            @Override
            public void onSuccess(BaseCallModel data) {
                mBtnSendCode.setEnabled(false);
                mCountDownTimer.start();
                mLoading.dismiss();
            }

            @Override
            public void onFail(ResponseError error) {
                mLoading.dismiss();
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    if (error.getCode() == 301010) {
                        showHasRegistedDialog(error.getMessage());
                    } else {
                        ToastUtil.s(error.getMessage());
                    }
                }
            }

            @Override
            public void onError() {
                mLoading.dismiss();
            }
        });


    }

    /**
     * 注册
     */
    @OnClick(R.id.btn_register)
    void toRegister() {
        if (!mBtnSelected.isSelected()) {
            ToastUtil.s(R.string.C_REGISTER_SERVICE_PROTOCOL_TIP);
            return;
        }
        String phone = mPhone.getText().toString().trim();
        String password = mPassword.getText().toString().trim();
        String code = mCode.getText().toString().trim();
        if (!AppHelper.checkPhoneAvailable(phone)) {
            ToastUtil.s(R.string.C_PHONE_INVALID);
            return;
        }

        if (!AppHelper.checkPwdAcailable(password)) {
            ToastUtil.s(R.string.C_PASSWORD_INVALID);
            return;
        }

        if (TextUtils.isEmpty(code)) {
            ToastUtil.s(R.string.C_INPUT_MESSAGE_CODE_HINT);
            return;
        }
        AppHelper.sendStatistics("zhuce", new String[]{getString(R.string.C_TERMINAL)}, new String[]{Build.BOARD});
        JSONObject params = new JSONObject();
        params.put("loginSource", "1");
        params.put("mobile", phone);
        params.put("passWord", password);
        params.put("smsCode", code);
        params.put("pushKey", CommonApp.STORE.getString(Constants.KEY_PUSH_CLIENT_ID, ""));
        mLoading.show();
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<UserInfoModel>> regist = requestService.regist(params);
        regist.enqueue(new ResponseCallback<BaseCallModel<UserInfoModel>>(this) {
            @Override
            public void onSuccess(BaseCallModel<UserInfoModel> data) {
                mLoading.dismiss();
                UserInfoModel userInfoModel = data.data;
                CommonApp.setUserInfo(userInfoModel);
                EventBus.getDefault().post(new CommonEvent(EventWhat.EVENT_LOGIN));
                RegistActivity.super.onBackPressed();
            }

            @Override
            public void onFail(ResponseError error) {
                mLoading.dismiss();
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    if (error.getCode() == 301010) {
                        showHasRegistedDialog(error.getMessage());
                    } else {
                        ToastUtil.s(error.getMessage());
                    }
                }
            }

            @Override
            public void onError() {
                mLoading.dismiss();
            }
        });

    }

    @OnClick(R.id.btn_delete)
    void toDelete() {
        mPhone.setText("");
    }

    @Override
    protected int layout() {
        return R.layout.act_regist;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPhone.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
        mPhone.addTextChangedListener(this);
        mPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppHelper.sendStatistics("zcshushouji");
            }
        });
        mPassword.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
        mPassword.addTextChangedListener(new InputEditTextWatcher(mLockState));
        mPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppHelper.sendStatistics("zcshumima");
            }
        });
        mPassword.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                AppHelper.sendStatistics("zcshumima");
                return false;
            }
        });
        mCode.addTextChangedListener(new InputEditTextWatcher(mKeyState));
        mCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppHelper.sendStatistics("zcshuruyzm");
            }
        });
        mCode.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                AppHelper.sendStatistics("zcshuruyzm");
                return false;
            }
        });

        mBtnSelected.setSelected(true);
        mText.setText(R.string.C_AGE_18_AGREE);
        mBtnProtocol.setText(R.string.C_REGISTER_SERVICE_PROTOCOL);
        mLoading = new DefLoading(this);

    }

    private void showHasRegistedDialog(String message) {
        BaseAlertDialog dialog = new BaseAlertDialog(this);
        dialog.setMessage(message);
        dialog.setPositiveButton(R.string.C_GOING_TO_LOGIN, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        dialog.show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCountDownTimer.cancel();
        mCountDownTimer = null;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String text = s.toString().trim();
        mBtnDelete.setVisibility(TextUtils.isEmpty(text) ? View.GONE : View.VISIBLE);
        mPhoneState.setSelected(!TextUtils.isEmpty(text));
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onBackPressed() {
        AppHelper.sendStatistics("zcfanhui");
        super.onBackPressed();
    }
}
